package com.un.ebs.workflow.aspect;

import com.un.ebs.core.exception.BusinessEntityNotFoundException;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.sys.service.ConfigureService;
import com.un.ebs.sys.service.UserGroupService;
import com.un.ebs.sys.service.UserService;
import com.un.ebs.sys.service.WxService;
import com.un.ebs.workflow.CostCode;
import com.un.ebs.workflow.domain.WorkflowInstance;
import com.un.ebs.workflow.domain.WorkflowNodeInstanceExt;
import com.un.ebs.workflow.service.WorkflowInstanceService;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Aspect
@Component
public class WorkflowInstanceServiceAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private WorkflowInstanceService workflowInstanceService;

    @Resource
    private UserGroupService userGroupService;

    @AfterReturning(value = "execution(* com.un.ebs.invoice.service.impl.InvoiceNoteServiceImpl.submit(String))", returning = "instanceId")
    public void invoiceSubmit(JoinPoint joinPoint, String instanceId) {
        startInstance(joinPoint, instanceId);
    }

    //@AfterReturning(value = "execution(* com.un.ebs.workflow.service.impl.WorkflowInstanceServiceImpl.start(String, String))", returning = "instanceId")
    public void startInstance(JoinPoint joinPoint, String instanceId) {
        if (StringUtils.isNullOrEmpty(instanceId)) {
            logger.warn(String.format("创建流程实例时，没有返回实例ID"));
            return;
        }
        WorkflowInstance instance = workflowInstanceService.queryById(instanceId);
        if (instance == null) {
            logger.warn(String.format("创建流程实例时，返回的实例ID没有找到相应的实例对象。"));
            throw new BusinessEntityNotFoundException(instanceId, "流程实例");
        }

        WorkflowNodeInstanceExt node = workflowInstanceService.queryCurrentTaskByInstance(instanceId);
        if (node == null) {
            logger.warn(String.format("没有找到流程实例的当前有效节点。"));
            return;
        }
        logger.debug(String.format("流程名称：%s，当前环节：%s", node.getWorkflowName(), node.getNodeName()));
        //System.out.println(String.format("流程名称：%s，当前环节：%s", node.getWorkflowName(), node.getNodeName()));

        List<String> ids = userGroupService.queryItem(null, node.getUserGroupId(), -1, 1).getRecords().stream().map(s -> s.getUserId()).distinct().collect(Collectors.toList());
        for (String userId : ids) {
            workflowInstanceService.sendPushNotify(userId, node);
        }
    }

    //@AfterReturning(value = "execution(* com.un.ebs.workflow.service.impl.WorkflowInstanceServiceImpl.taskPush(String,String,com.un.ebs.workflow.enums.NodePassTypeEnum))", returning = "ids")
    public void push(JoinPoint joinPoint, List<String> ids) {
        if (StringUtils.isNullOrEmpty(ids)) {
            logger.warn(String.format("流程【%s】Push时未返回节点实例ID", joinPoint.getArgs()[0]));
            return;
        }

        WorkflowNodeInstanceExt node = workflowInstanceService.queryTaskById(ids.get(0));
        if (node == null) {
            logger.warn(String.format("流程节点实例为空，【%s】消息发送取消。", ids.toString()));
            return;
        }
        logger.debug(String.format("流程名称：%s，当前环节：%s", node.getWorkflowName(), node.getNodeName()));

        for (String userId : userGroupService.queryItem(null, node.getUserGroupId(), -1, 1).getRecords().stream().map(s -> s.getUserId()).distinct().collect(Collectors.toList())) {
            workflowInstanceService.sendPushNotify(userId, node);
        }
    }


}
